package org.aplikator.client.shared.rpc.marshaller;

import org.aplikator.client.shared.data.ClientContext;
import org.aplikator.client.shared.data.Record;
import org.jboss.errai.marshalling.client.api.Marshaller;
import org.jboss.errai.marshalling.client.api.MarshallingSession;
import org.jboss.errai.marshalling.client.api.annotations.ClientMarshaller;
import org.jboss.errai.marshalling.client.api.annotations.ServerMarshaller;
import org.jboss.errai.marshalling.client.api.json.EJObject;
import org.jboss.errai.marshalling.client.api.json.EJValue;
import org.jboss.errai.marshalling.client.marshallers.AbstractNullableMarshaller;

@ClientMarshaller(ClientContext.class)
@ServerMarshaller(ClientContext.class)
public class ClientContextMarshaller extends AbstractNullableMarshaller<ClientContext> {

	/*@Override
	public Class<ClientContext> getTypeHandled() {
		return ClientContext.class;
	}*/

	@Override
	public ClientContext[] getEmptyArray() {
		return new ClientContext[0];
	}

	@Override
	public ClientContext doNotNullDemarshall(EJValue o, MarshallingSession ctx) {
		if (o.isObject() != null) {
			EJObject ejObject = o.isObject();
			ClientContext clientCtx = new ClientContext();
			if (DemarshallingUtils.containsAndNotNull(ejObject, "user")) {
				clientCtx.setUser(ejObject.get("user").isString().stringValue());
			}
			if (DemarshallingUtils.containsAndNotNull(ejObject, "locale")) {
				clientCtx.setLocale(ejObject.get("locale").isString().stringValue());
			}
			if (DemarshallingUtils.containsAndNotNull(ejObject, "currentRecord")) {
				Marshaller<Object> marshallerInstance = ctx.getMarshallerInstance(Record.class.getName());
				Object demarshalled = marshallerInstance.demarshall(ejObject.get("currentRecord"), ctx);
				clientCtx.setCurrentRecord((Record) demarshalled);
			}
			return clientCtx;
		} else return null;
	}

	@Override
	public String doNotNullMarshall(ClientContext o, MarshallingSession ctx) {
		StringBuilder builder = new StringBuilder().append('{');
		MarshallingUtils.string("user", o.getUser(), builder).append(',');
		MarshallingUtils.string("locale", o.getLocale(), builder).append(',');
		MarshallingUtils.key("currentRecord", builder).append(':');
		Marshaller<Object> marshaller = ctx.getMarshallerInstance(Record.class.getName());
		builder.append(marshaller.marshall(o.getCurrentRecord(), ctx));
		builder.append('}');
		return builder.toString();
	}

}
